package com.qiwenshare.file.file_encryption;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;


/**
 * @author 成琪
 * @version 1.0
 * @date 2022-01-04 10:49
 */
public class SM4Utilis {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    //定义ALGORITHM_NAME为SM4算法
    public static final String ALGORITHM_NAME = "SM4";
    //定义默认种子DEFAULT_KEY
    public static final String DEFAULT_KEY = "random_seed";
    //分组长度
    public static final int DEFAULT_KEY_SIZE = 128;


    //默认种子，默认秘钥长度，生成密钥
    public static byte[] generateKey() throws NoSuchAlgorithmException, NoSuchProviderException {
        return generateKey(DEFAULT_KEY, DEFAULT_KEY_SIZE);
    }
    //给定种子，默认秘钥长度，生成密钥
    public static byte[] generateKey(String seed) throws NoSuchAlgorithmException, NoSuchProviderException {
        return generateKey(seed, DEFAULT_KEY_SIZE);
    }
    //给定种子，给定秘钥长度，生成密钥
    public static byte[] generateKey(String seed, int keySize) throws NoSuchAlgorithmException, NoSuchProviderException {
        //SM4算法生成密钥的KeyGenerator对象
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME,BouncyCastleProvider.PROVIDER_NAME);
        //用SHA1PRNG随机数算法生成SecureRandom对象
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        //当种子不为空时，用给定的种子重新播种随机对象
        if (null != seed && !"".equals(seed)) {
            random.setSeed(seed.getBytes());
        }
        //密钥初始化
        kg.init(keySize, random);
        //返回生成的密钥
        return kg.generateKey().getEncoded();
    }

    //加密
    public static byte[] encrypt(String algorithmName, byte[] key, byte[] iv, byte[] data) throws Exception {
        return sm4core(algorithmName, Cipher.ENCRYPT_MODE, key, iv, data);
    }

    //解密
    public static byte[] decrypt(String algorithmName, byte[] key, byte[] iv, byte[] data) throws Exception {
        return sm4core(algorithmName, Cipher.DECRYPT_MODE, key, iv, data);
    }

    //CTR模式加解密
    private static byte[] sm4core(String algorithmName, int type, byte[] key, byte[] iv, byte[] data) throws Exception {
        //创建Cipher对象，实例化加密类
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        //两个参数，第一个为私钥字节数组， 第二个为加密方式
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        //创建IvParameterSpec对象
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        //初始化，此方法可以采用三种方式，按服务器要求来添加。
        // （1）无第三个参数
        // （2）第三个参数为SecureRandom random = new SecureRandom();中的random对象，随机数。
        // （3）采用此代码中的IVParameterSpec
        cipher.init(type, sm4Key, ivParameterSpec);
        //返回加解密后的字节数组
        return cipher.doFinal(data);
    }


}
